using PKGames.Voxel;
using UnityEngine;

namespace PKGames
{
	public class WindowTransitionController : MonoBehaviour
	{
		private static WindowTransitionController _instance;

		private bool _disableLastWindow;

		private bool _destroyAfterTransition = true;

		[SerializeField]
		private RectTransform _canvasRect;

		public static WindowTransitionController Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = (WindowTransitionController)UnityEngine.Object.FindObjectOfType(typeof(WindowTransitionController));
				}
				return _instance;
			}
		}

		public void RunOpenPageTransition(AbstractWindow lastWindow, AbstractWindow nextWindow, bool destroyLastWindow = false, bool disableLastWindow = true)
		{
			_disableLastWindow = disableLastWindow;
			_destroyAfterTransition = destroyLastWindow;
			if (nextWindow != null)
			{
				if (nextWindow.IsPortrait && !IsDeviceInPortrait())
				{
					nextWindow.RotationTransition.InitializeTransition(lastWindow, nextWindow);
					nextWindow.RotationTransition.InitOpenWindowTransition(FinishedOpenPageTransition, _canvasRect);
				}
				else
				{
					nextWindow.WindowTransition.InitializeTransition(lastWindow, nextWindow);
					nextWindow.WindowTransition.InitOpenWindowTransition(FinishedOpenPageTransition, _canvasRect);
				}
			}
		}

		private bool IsDeviceInPortrait()
		{
			return ApplicationManager.GetScreenOrientation() == ScreenOrientation.Portrait || ApplicationManager.GetScreenOrientation() == ScreenOrientation.PortraitUpsideDown;
		}

		private void FinishedOpenPageTransition(AbstractWindow lastWindow, AbstractWindow nextWindow)
		{
			if (_destroyAfterTransition && lastWindow != null)
			{
				lastWindow.DestroyWindow();
			}
			else if (_disableLastWindow && lastWindow != null)
			{
				lastWindow.WindowHolder.gameObject.SetActive(value: false);
			}
		}

		public void RunClosePageTransition(AbstractWindow lastWindow, AbstractWindow nextWindow)
		{
			if (IsExpectedLandscape(nextWindow) && ApplicationManager.GetScreenOrientation() == ScreenOrientation.Portrait)
			{
				lastWindow.RotationTransition.InitializeTransition(lastWindow, nextWindow);
				lastWindow.RotationTransition.InitClosePageTransition(FinishedClosePageTransition, _canvasRect);
			}
			else
			{
				lastWindow.WindowTransition.InitializeTransition(lastWindow, nextWindow);
				lastWindow.WindowTransition.InitClosePageTransition(FinishedClosePageTransition, _canvasRect);
			}
		}

		private bool IsExpectedLandscape(AbstractWindow nextWindow)
		{
			return nextWindow == null || !nextWindow.IsPortrait;
		}

		private void FinishedClosePageTransition(AbstractWindow lastWindow, AbstractWindow nextWindow)
		{
			lastWindow.DestroyWindow();
		}
	}
}
